package io.webfolder.cdp.channel;

import static com.neovisionaries.ws.client.WebSocketCloseCode.NORMAL;

import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketException;
//import com.neovisionaries.ws.client.ZeroMasker;

import io.webfolder.cdp.exception.CdpException;

public class NvWebSocketChannel implements Channel {

	private final WebSocket webSocket;

	NvWebSocketChannel(WebSocket webSocket) {
		this.webSocket = webSocket;
		this.webSocket.setDirectTextMessage(true);
		this.webSocket.setAutoFlush(true);
	}

	@Override
	public boolean isOpen() {
		return webSocket.isOpen();
	}

	@Override
	public void disconnect() {
		try {
			webSocket.sendClose(CLOSE_STATUS_CODE, CLOSE_REASON_TEXT);
			webSocket.disconnect(NORMAL, null, 1000); // max wait time to close: 1 seconds
		} catch (Throwable t) {
			// ignore
		}
	}

	@Override
	public void sendText(String message) {
		webSocket.sendText(message);
	}

	@Override
	public void connect() {
		try {
			webSocket.connect();
		} catch (WebSocketException e) {
			throw new CdpException(e);
		}
	}
}
